<?php

namespace App\Http\Controllers;

use App\Models\Buy;
use App\Models\User;
use Illuminate\Http\Request;

class AgentController extends Controller
{
    public function indexForAdmin(Request $request)
    {
        $page = User::latest()
            ->when($request->has('username'), function ($q) use ($request) {
                $q->where('username', $request->username);
            })
            ->when($request->has('code'), function ($q) use ($request) {
                $q->where('code', $request->code);
            })
            ->when($request->has('created_at'), function ($q) use ($request) {
                $range = getRange($request->created_at);
                $q->whereBetween('created_at', $range);
            })
            ->where('role', 'agent')
            ->page();

        $page->transform(function ($item) {
            $item->makeVisible('code');
            return $item;
        });

        return success($page);
    }

    public function accounts(Request $request)
    {

        $page = $this->accountsQueryBuilder($request)
            ->page();
        $page->transform(function ($item) {
            $item->tip_fee += 0;
            $item->fee_sum += 0;
            $item->tip_sum += 0;
            return $item;
        });
        $all = $this->accountsQueryBuilder($request)->get();
        $footer = [
            '汇总',
            '',
            $all->sum('tip_fee'),
            $all->sum('fee_sum'),
            $all->sum('tip_sum'),
            $all->sum('cut'),
            $all->sum('subs_count'),
        ];
        return success($page, $footer);
    }

    protected function accountsQueryBuilder($request)
    {
        return User::select('id', 'username', 'coins', 'cut')
            ->when($request->has('username'), function ($q) use ($request) {
                $q->where('username', $request->username);
            })
            ->when($request->has('created_at'), function ($q) use ($request) {
                $range = getRange($request->created_at);

                $q->with(['agentBoughts' => function ($q) use ($range) {
                    $q->whereBetween('buy.updated_at', $range);
                }])
                    ->addSelect([
                        'tip_fee' => Buy::groupSumForUser('sum(agent_tip_fee)', 'agent_id')
                            ->whereBetween('buy.updated_at', $range),
                        'fee_sum' => Buy::groupSumForUser('sum(agent_fee)', 'agent_id')
                            ->whereBetween('buy.updated_at', $range),
                        'tip_sum' => Buy::groupSumForUser('sum(agent_tip)', 'agent_id')
                            ->whereBetween('buy.updated_at', $range),
                    ]);
            }, function ($q) {
                $q->with('agentBoughts')
                    ->addSelect([
                        'tip_fee' => Buy::groupSumForUser('sum(agent_tip_fee)', 'agent_id'),
                        'fee_sum' => Buy::groupSumForUser('sum(agent_fee)', 'agent_id'),
                        'tip_sum' => Buy::groupSumForUser('sum(agent_tip)', 'agent_id')
                    ]);
            })
            ->withCount('subs')
            ->where('role', 'agent');
    }

    public function store(Request $request)
    {
        $input = $request->all();
        $input['role'] = 'agent';
        $input['password'] = bcrypt($request->password);
        $input['code'] = makeCode();
        User::create($input);
        return success('ok');
    }

    public function show()
    {
    }

    public function update(Request $request, $id)
    {
        $agent = User::findOrFail($id);
        $input = $request->except('password');
        if ($request->filled('password')) {
            $input['password'] = bcrypt($request->password);
        }
        if ($request->fee_ratio) {
            if ($request->fee_ratio < $agent->fee_ratio) {
                fail('不能低于当前设定值');
            }
        }
        if ($request->tip) {
            if ($request->tip < $agent->tip) {
                fail('不能低于当前设定值');
            }
        }
        $agent->update($input);
        return success('ok');
    }

    public function drawCoins($id, Request $request)
    {
        $agent = User::findOrFail($id);
        $agent->cut = bcadd($agent->cut, $request->coins, 3);
        $agent->coinsChange(-$request->coins, '提取佣金');
        return success('ok');
    }

    public function destroy()
    {
        //
    }
}
